from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
import Ui_jurnal
import master.utility as utility
import jurnalEdit

class Jurnal(QDialog, Ui_jurnal.Ui_JurnalDlg):
  def __init__(self, dbConn, dataGlob,  parent=None):
        super(Jurnal, self).__init__(parent)
        self.setupUi(self)
        self.initMenu()
        self.tgl_cb.setCheckState(Qt.Checked)
        self.tgl_aw.setDate(QDate.currentDate())
        self.tgl_ak.setDate(QDate.currentDate())
        self.db = dbConn
        self.dataGlob = dataGlob
        self.util = utility.Utility(self.db)
        
        self.mastModel = QSqlQueryModel(self)
        self.mastModel.setHeaderData(0, Qt.Horizontal, QVariant("Date"))
        self.mastModel.setHeaderData(1, Qt.Horizontal, QVariant("Type"))
        self.mastModel.setHeaderData(2, Qt.Horizontal, QVariant("Journal No"))
        self.mastModel.setHeaderData(3, Qt.Horizontal, QVariant("Description"))
        self.mastModel.setHeaderData(4, Qt.Horizontal, QVariant("Reference"))
        self.mastModel.setHeaderData(5, Qt.Horizontal, QVariant("Relation/Unit"))
        self.mastModel.setHeaderData(6, Qt.Horizontal, QVariant("Journal Ref"))
        self.mastModel.setHeaderData(7, Qt.Horizontal, QVariant("Due Date"))
        self.mastModel.setHeaderData(8, Qt.Horizontal, QVariant("Audit User"))
        self.mastModel.setHeaderData(12, Qt.Horizontal, QVariant("Audit Time"))
        
        self.master_tbv.setModel(self.mastModel)
        self.master_tbv.setItemDelegate(MasterDelegate(self))
        self.master_tbv.setSelectionMode(QTableView.SingleSelection)
        self.master_tbv.setSelectionBehavior(QTableView.SelectRows)
        self.connect(self.master_tbv.selectionModel(), SIGNAL("currentRowChanged(QModelIndex,QModelIndex)"), self.rowChanged)
        
        self.detModel = QSqlQueryModel(self)
        self.detModel.setHeaderData(0, Qt.Horizontal, QVariant("COA Code"))
        self.detModel.setHeaderData(1, Qt.Horizontal, QVariant("COA Name"))
        self.detModel.setHeaderData(3, Qt.Horizontal, QVariant("Debet (Rp)"))
        self.detModel.setHeaderData(4, Qt.Horizontal, QVariant("Kredit (Rp)"))
        
        self.detail_tbv.setModel(self.detModel)
        self.detail_tbv.setItemDelegate(DetailDelegate(self))
        self.detail_tbv.setSelectionMode(QTableView.SingleSelection)
        self.detail_tbv.setSelectionBehavior(QTableView.SelectRows)
        
        self.coaModel = QSqlQueryModel(self)
        self.coaModel.setQuery("select kode_perkiraan, nama from master_kode_perkiraan where detail = 'Y' order by kode_perkiraan", self.db)
        self.coa_cmb.setModel(self.coaModel)
        self.coa_cmb.setModelColumn(1)
        self.coa_cmb.setCurrentIndex(0)
        self.coa_cb.setCheckState(Qt.Unchecked)
                
        
  @pyqtSignature("")
  def on_no_le_editingFinished(self):
      if self.no_le.text() != "":
          self.no_cb.setCheckState(Qt.Checked)
      else:
          self.no_cb.setCheckState(Qt.Unchecked)
        
  @pyqtSignature("int")
  def on_coa_cmb_currentIndexChanged(self, idx):
      self.coa_cb.setCheckState(Qt.Checked)
          
  @pyqtSignature("")
  def on_tgl_aw_editingFinished(self):
      self.tgl_cb.setCheckState(Qt.Checked)
          
  @pyqtSignature("")
  def on_tgl_ak_editingFinished(self):
      self.tgl_cb.setCheckState(Qt.Checked)
          
  @pyqtSignature("")
  def on_desc_le_editingFinished(self):
      if self.desc_le.text() != "":
          self.desc_cb.setCheckState(Qt.Checked)
      else:
          self.desc_cb.setCheckState(Qt.Unchecked)
          
  @pyqtSignature("")
  def on_unit_le_editingFinished(self):
      if self.unit_le.text() != "":
          self.unit_cb.setCheckState(Qt.Checked)
      else:
          self.unit_cb.setCheckState(Qt.Unchecked)
          
  @pyqtSignature("")
  def on_ref_le_editingFinished(self):
      if self.ref_le.text() != "":
          self.ref_cb.setCheckState(Qt.Checked)
      else:
          self.ref_cb.setCheckState(Qt.Unchecked)
          
  @pyqtSignature("")
  def on_valid_cmb_editingFinished(self):
      self.valid_cb.setCheckState(Qt.Checked)
          
  @pyqtSignature("")
  def on_refJ_le_editingFinished(self):
      if self.refJ_le.text() != "":
          self.refJ_cb.setCheckState(Qt.Checked)
      else:
          self.refJ_cb.setCheckState(Qt.Unchecked)
          
  def initMenu(self):
      self.retrieveAct = QAction(QIcon(":/retrieve.ico"), self.tr("Retrieve"), self)
#      self.retrieveAct.setShortcut ("Ctrl+R")
      self.connect(self.retrieveAct, SIGNAL("triggered()"), self.retrieveData)
      self.sortAct = QAction(QIcon(":/sort.ico"), self.tr("Sort"), self)
#      self.sortAct.setShortcut ("Ctrl+S")
      self.addAct = QAction(QIcon(":/add.ico"), self.tr("Add"), self)
#      self.addAct.setShortcut ("Ctrl+A")
      self.connect(self.addAct, SIGNAL("triggered()"), self.addData)
      self.editAct = QAction(QIcon(":/edit.ico"), self.tr("Edit"), self)
#      self.editAct.setShortcut ("Ctrl+E")
      self.connect(self.editAct, SIGNAL("triggered()"), self.editData)
      self.delAct = QAction(QIcon(":/del.ico"), self.tr("Delete"), self)
      self.connect(self.delAct, SIGNAL("triggered()"), self.delData)
#      self.delAct.setShortcut ("Ctrl+Del")
      self.printAct = QAction(QIcon("res/print.ico"), self.tr("Print Preview"), self)
      self.connect(self.printAct, SIGNAL("triggered()"), self.printData)
#      self.printAct.setShortcut ("Ctrl+P")

  def retrieveData(self):
      qStr = "select distinct date_format(m.tgl_jurnal,'%d-%m-%Y'), m.jurnal_type, m.no_jurnal, m.desk_jurnal, m.no_ref, m.kode_client, m.cab, date_format(m.jatuh_tempo,'%d-%m-%Y'), date_format(m.kode_user,'%d-%m-%Y'), m.tgl_entry,  m.kode_buyer, m.kode_periode, m.audit_time from trans_jurnal m "\
      "left outer join trans_jurnal_detail d on d.no_jurnal = m.no_jurnal"
      
      filt = ""
      urut = " order by m.tgl_jurnal, m.desk_jurnal "
      if self.no_cb.checkState() == Qt.Checked:
          filt = filt + " m.no_jurnal like '"+self.no_le.text()+"%' and "
      if self.coa_cb.checkState() == Qt.Checked:
          brs = self.coaModel.currentIndex()
          kode = self.coaModel.data(self.coaModel.index(brs, 0)).toString()
          filt = filt + " d.kode_perkiraan = '"+kode+"' and "
      if self.tgl_cb.checkState() == Qt.Checked:
          filt = filt + " m.tgl_jurnal between '"+self.tgl_aw.date().toString("yyyy-MM-dd")+"' and '"+self.tgl_ak.date().toString("yyyy-MM-dd")+"' and "
      if self.desc_cb.checkState() == Qt.Checked:
          filt = filt + " m.desk_jurnal like '"+self.desc_le.text()+"%' and "
      if self.unit_cb.checkState() == Qt.Checked:
          filt = filt + " m.kode_client like '"+self.unit_le.text()+"%' and "
      if self.ref_cb.checkState() == Qt.Checked:
          filt = filt + " m.no_ref like '"+self.ref_le.text()+"%' and "
      if self.refJ_cb.checkState() == Qt.Checked:
          filt = filt + " m.cab like '"+self.refJ_le.text()+"%' and "
          
      if filt != "":
          filt = " where "+filt.left(len(filt)-4)
          
      qStr = qStr + filt + urut
      self.mastModel.setQuery(qStr, self.db)
      self.master_tbv.setColumnHidden(9, True)
      self.master_tbv.setColumnHidden(10, True)
      self.master_tbv.setColumnHidden(11, True)
      self.master_tbv.setColumnWidth(0, 80)
      self.master_tbv.setColumnWidth(1, 50)
      self.master_tbv.setColumnWidth(3, 400)
      self.master_tbv.resizeRowsToContents()
      
  def addData(self):
      form = jurnalEdit.JurnalEdit(self.db, "add",  self.dataGlob, self)
      form.show()

  def editData(self):
      index = self.master_tbv.currentIndex()
      if index.isValid():
          brs = self.mastModel.record(index.row())
          id = brs.value("no_jurnal").toString()
          form = jurnalEdit.JurnalEdit(self.db, id, self.dataGlob, self)
          form.show()

  def delData(self):
      index = self.master_tbv.currentIndex()
      if index.isValid():
          brs = self.mastModel.record(index.row())
          id = brs.value("no_jurnal").toString()
          if QMessageBox.question(self, "Journal","Delete Dok No : "+id+"?", QMessageBox.Yes|QMessageBox.No) == QMessageBox.Yes:
              qMast = QSqlQuery(self.db)
              qDet = QSqlQuery(self.db)
              self.db.transaction()
              qDet.exec_("delete from trans_jurnal_detail where no_jurnal = '"+id+"'")
              qMast.exec_("delete from trans_jurnal where no_jurnal = '"+id+"'")
              self.db.commit()
              self.retrieveData()
              self.rowChanged()

  def sortData(self):
       qStr = "select id_pelanggan, kode_pelanggan, nama, no_kartu, alamat1, kota1 from pelanggan"
       self.mastModel.setQuery(qStr, self.db)

  def printData(self):
      self.dialog = QPrintPreviewDialog()
      self.connect(self.dialog, SIGNAL("paintRequested(QPrinter *)"), self.printPreview)
      self.dialog.exec_()
       
  def printPreview(self,  printer):
      painter = QPainter()
      painter.begin(printer)
      index = self.master_tbv.currentIndex()
      if not index.isValid():
          return
      brs = self.mastModel.record(index.row())
      id = brs.value("no_jurnal").toString()
      myfont = QFont("Arial", 11)
      painter.setFont(myfont)
      kiri = 50
      line = 100
      lineH = 20
      painter.drawRect(600, 20, 150, 25)
      painter.drawText(650, 35, "JOURNAL")
      myfont.setPointSize(8)
      painter.setFont(myfont)
      painter.drawText(600, 60, "Print Date : "+self.util.getServerToday().toString("dd-MM-yyyy hh:mm"))
      painter.drawText(kiri, line,"Journal Date ")
      painter.drawText(kiri+70, line, ": ")
      painter.drawText(kiri+80, line, brs.value("tgl_jurnal").toDate().toString("dd-MM-yyyy"))
      
      painter.drawText(kiri+250, line,"Due Date : "+brs.value("jatuh_tempo").toDate().toString("dd-MM-yyyy"))
      painter.drawText(kiri+500, line,"Journal No ")
      painter.drawText(kiri+570, line, ": ")
      painter.drawText(kiri+580, line, id)
      
      line += lineH
      painter.drawText(kiri, line,"Description ")
      painter.drawText(kiri+70, line, ": ")
      painter.drawText(kiri+80, line, brs.value("desk_jurnal").toString())
      line += lineH
      painter.drawText(kiri, line,"Bank Date ")
      painter.drawText(kiri+70, line, ": ")
      painter.drawText(kiri+80, line, brs.value("tgl_entry").toDate().toString("dd-MM-yyyy"))
      painter.drawText(kiri+500, line,"Journal Ref. ")
      painter.drawText(kiri+570, line, ": ")
      painter.drawText(kiri+580, line, brs.value("cab").toString())
      line += lineH
      painter.drawText(kiri, line,"Ref No ")
      painter.drawText(kiri+70, line, ": ")
      painter.drawText(kiri+80, line, brs.value("no_ref").toString())
      painter.drawText(kiri+500, line,"Unit : ")
      painter.drawText(kiri+570, line, ": ")
      painter.drawText(kiri+580, line, brs.value("kode_client").toString())      
      line += 10
      painter.drawLine(kiri , line,  750,  line)
      line += lineH
      painter.drawText(kiri,  line,  "No")
      painter.drawText(kiri+30,  line,  "Account Code")
      painter.drawText(kiri+120,  line,  "Description")
      painter.drawText(kiri+520,  line,  "Debit")
      painter.drawText(kiri+670,  line,  "Credit")            
      line += 10
      painter.drawLine(kiri , line,  750,  line)
      totBrs = self.detModel.rowCount()
      option = QTextOption(Qt.AlignRight)
      option.setWrapMode(QTextOption.WordWrap)
      debSum = 0
      creSum = 0
      for i in range(totBrs):
          line += lineH
          record = self.detModel.record(i)
          painter.drawText(kiri, line,  str(i+1))
          painter.drawText(kiri+30, line,  record.value(0).toString())
          painter.drawText(kiri+120, line,  record.value(1).toString())
          deb = record.value(3).toDouble()[0]
          debSum += deb
          painter.drawText(QRectF(kiri+350, line-10, 200, 20), QString("%L1").arg(float(deb), 0, "f", 2), option)
          cre = record.value(4).toDouble()[0]
          creSum += cre
          painter.drawText(QRectF(kiri+500, line-10, 200, 20), QString("%L1").arg(float(cre), 0, "f", 2), option)
          painter.drawLine(kiri , line+5,  750,  line+5)
      
      line += lineH
      painter.drawText(QRectF(kiri+350, line-10, 200, 20), QString("%L1").arg(float(debSum), 0, "f", 2), option)
      painter.drawText(QRectF(kiri+500, line-10, 200, 20), QString("%L1").arg(float(creSum), 0, "f", 2), option)
      
      line += lineH+10
      painter.drawText(kiri+50,  line,  "Prepared By,")
      painter.drawText(kiri+550,  line,  "Approved By,")
      
      line += 80
      painter.drawLine(kiri+15, line,  kiri+135,  line)
      painter.drawLine(kiri+450 , line,  kiri+570,  line)
      painter.drawLine(kiri+580 , line,  kiri+700,  line)
      line += lineH
      painter.drawText(kiri+30,  line,  "Finance/Accounting")
      painter.drawText(kiri+470,  line,  "Chief Finance/Acc")
      painter.drawText(kiri+600,  line,  "General Manager")
      painter.end()
      
  def contextMenuEvent(self, event):
        menu = QMenu(self)
        menu.addAction(self.retrieveAct)
        menu.addAction(self.sortAct)
        menu.addSeparator()
        menu.addAction(self.addAct)
        menu.addAction(self.editAct)
        menu.addSeparator()
        menu.addAction(self.delAct)
        menu.addSeparator()
        menu.addAction(self.printAct)
        menu.exec_(event.globalPos())

  def rowChanged(self):
      index = self.master_tbv.currentIndex()
      if index.isValid():
          record = self.mastModel.record(index.row())
          id = record.value("no_jurnal").toString()
          qStr = "select d.kode_perkiraan, k.nama, d.no_jurnal, format(d.debit,2), format(d.kredit,2), d.urut from trans_jurnal_detail d "\
          "left outer join master_kode_perkiraan k on k.kode_perkiraan = d.kode_perkiraan "\
          "where d.no_jurnal = '"+id+"'"
          self.detModel.setQuery(qStr, self.db)
      self.detail_tbv.setColumnHidden(2, True)
      self.detail_tbv.setColumnHidden(5, True)      
      self.detail_tbv.setColumnWidth(2, 300)
      self.detail_tbv.resizeRowsToContents()
      
  def hitungTotal(self):
      totBrs = self.mastModel.rowCount()
#      rpTot = 0
#      poinTot = 0
#      for i in range(totBrs):
#          record = self.mastModel.record(i)
#          rpTot += record.value(TOTAL_RP).toDouble()[0]
#          poinTot += record.value(POIN).toDouble()[0]
#      self.totalRp.setText(str(rpTot))
#      self.totalPoin.setText(str(poinTot))

class MasterDelegate(QItemDelegate):
    def __init__(self, parent=None):
        super(MasterDelegate, self).__init__(parent)
        
    def paint(self, painter, option, index):
        myoption = QStyleOptionViewItem(option)
        if index.column() == 0:
            myoption.displayAlignment |= Qt.AlignRight|Qt.AlignVCenter
        QItemDelegate.paint(self, painter, myoption, index)        
        
#    def drawDisplay(self, painter, option, rect,  text):
#        dat = QDate.fromString(text, Qt.SystemLocaleDate)
#        if dat.isValid():
#            QItemDelegate.drawDisplay(self, painter, option, rect, dat.toString("dd-MM-yyyy"))
#        else:
#            QItemDelegate.drawDisplay(self, painter, option, rect, text)
            
            
class DetailDelegate(QItemDelegate):
    def __init__(self, parent=None):
        super(DetailDelegate, self).__init__(parent)
        
    def paint(self, painter, option, index):
        myoption = QStyleOptionViewItem(option)
        if index.column() == 3 or index.column() == 4:
            myoption.displayAlignment |= Qt.AlignRight|Qt.AlignVCenter
        QItemDelegate.paint(self, painter, myoption, index)
        
if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    form = Jurnal()
    form.show()
    app.exec_()
